const loadConfig = require('../util/loadconfig'),
	iamNameSanitize = require('../util/iam-name-sanitize'),
	aws = require('aws-sdk');

module.exports = function addIOTTopicRuleEventSource(options) {
	'use strict';
	let lambdaConfig,
		lambda,
		ruleName,
		iot;
	const initServices = function () {
			lambda = new aws.Lambda({region: lambdaConfig.region});
			iot = new aws.Iot({region: lambdaConfig.region});
		},
		readConfig = function () {
			return loadConfig(options, {lambda: {name: true, region: true}})
				.then(config => lambdaConfig = config.lambda)
				.then(initServices)
				.then(() => lambda.getFunctionConfiguration({FunctionName: lambdaConfig.name, Qualifier: options.version}).promise())
				.then(result => {
					lambdaConfig.arn = result.FunctionArn;
					lambdaConfig.version = result.Version;
				}).then(() => {
					ruleName = options.ruleName || 'lambda_' + Date.now();
				});
		},
		addInvokePermission = function (ruleArn) {
			return lambda.addPermission({
				Action: 'lambda:InvokeFunction',
				FunctionName: lambdaConfig.name,
				Principal: 'iot.amazonaws.com',
				SourceArn: ruleArn,
				Qualifier: options.version,
				StatementId: iamNameSanitize(ruleName + '-' + Date.now())
			}).promise().then(() => ruleArn);
		},
		getRuleArn = function () {
			return iot.getTopicRule({ruleName: ruleName})
				.promise()
				.then(result => result.ruleArn);
		},
		addRule = function () {
			return iot.createTopicRule({
				ruleName: ruleName,
				topicRulePayload: {
					sql: options.sql,
					awsIotSqlVersion: options.sqlVersion,
					description: options.description,
					ruleDisabled: false,
					actions: [{
						lambda: {
							functionArn: lambdaConfig.arn
						}
					}]
				}
			}).promise();
		},
		formatResult = function (ruleArn) {
			return {
				ruleName: ruleName,
				ruleArn: ruleArn
			};
		};
	if (!options.sql) {
		return Promise.reject('SQL statement not specified. please provide it with --sql');
	}

	return readConfig()
		.then(addRule)
		.then(getRuleArn)
		.then(addInvokePermission)
		.then(formatResult);
};
module.exports.doc = {
	description: 'Creates an IOT topic rule and configures the Lambda to run when a message is published on a matching IOT Gateway topic',
	priority: 5,
	args: [
		{
			argument: 'sql',
			description: 'the IOT SQL Statement for the topic filter, see http://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-reference.html',
			example: 'SELECT * FROM \'iot/+\''
		},
		{
			argument: 'ruleName',
			optional: true,
			description: 'The name of the topic rule',
			example: 'temperaturecheck',
			default: 'a random autogenerated name'
		},
		{
			argument: 'description',
			optional: true,
			description: 'topic rule description',
			example: 'Checks temperature limits',
			default: 'empty'
		},
		{
			argument: 'sqlVersion',
			optional: true,
			description: 'IOT SQL Language version used in the SQL statement, see http://docs.aws.amazon.com/iot/latest/developerguide/iot-rule-sql-version.html',
			example: 'beta',
			default: '2015-10-08'
		},
		{
			argument: 'version',
			optional: true,
			description: 'Bind to a particular version',
			example: 'production',
			default: 'latest version'
		},
		{
			argument: 'source',
			optional: true,
			description: 'Directory with project files',
			default: 'current directory'
		},
		{
			argument: 'config',
			optional: true,
			description: 'Config file containing the resource names',
			default: 'claudia.json'
		}
	]
};
